package com.mutouren.common.mq;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.mutouren.common.log.LogManager;
import com.mutouren.common.log.Logger;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class RabbitMQSource {
	private static Logger errorLogger = LogManager.getLogger("SystemErrorLog");
	private static Map<String, Connection> mapConnection = new HashMap<String, Connection>();

	public static Channel getChannel(String serverName) throws IOException {
		try {
			return getConnection(serverName).createChannel();
		} catch (IOException t) {
			errorLogger.error(String.format("RabbitMQSource.createConnection() error! server: %s", serverName), t);
			throw t;
		}
	}

	private synchronized static Connection getConnection(String serverName) throws IOException {
		Connection result;
		if (mapConnection.containsKey(serverName)) {
			result = mapConnection.get(serverName);
		} else {
			RabbitMQConfig config = new RabbitMQConfig(serverName);
			result = createConnection(config);
			mapConnection.put(serverName, result);
		}
		return result;
	}

	private synchronized static Connection createConnection( RabbitMQConfig config) throws IOException {
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost(config.getIp());
		factory.setPort(config.getPort());
		factory.setUsername(config.getUserName());
		factory.setPassword(config.getPassword());
		return factory.newConnection();
	}

}
